package com.big.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.big.cmn.DictFeignClient;
import com.big.common.exception.BigException;
import com.big.common.result.ResultCodeEnum;
import com.big.common.utils.UUIDGenerator;
import com.big.merchandise.MerchandiseFeignClient;
import com.big.model.model.merchandise.MerchandiseDetail;
import com.big.model.model.merchandise.comment.MerchandiseComment;
import com.big.model.model.order.MerchandiseOrder;
import com.big.model.model.patient.PatientInfo;
import com.big.model.model.patient.address.PatientAddress;
import com.big.model.model.record.MerchandiseOrderRecord;
import com.big.model.vo.merchandise.MerchanCommVo;
import com.big.model.vo.order.OrderInfoQueryVo;
import com.big.model.vo.order.OrderVo;
import com.big.model.vo.pay.AlipayTradeQueryResponseVo;
import com.big.model.vo.sms.PaySmsVo;
import com.big.order.mapper.MerchandiseOrderMapper;
import com.big.order.service.OrderRecordService;
import com.big.order.service.OrderService;
import com.big.patient.PatientFeignClient;
import com.big.pay.PayFeignClient;
import com.big.sms.SmsFeignClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.concurrent.ExecutionException;

@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<MerchandiseOrderMapper, MerchandiseOrder> implements OrderService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    PatientFeignClient patientFeignClient;

    @Autowired
    MerchandiseFeignClient merchandiseFeignClient;

    @Autowired
    OrderRecordService merchandiseOrderRecordService;

    @Autowired
    PayFeignClient payFeignClient;


    @Autowired
    DictFeignClient dictFeignClient;


    @Autowired
    SmsFeignClient smsFeignClient;
    /**
     * 创建订单
     */
    @Override
//    @GlobalTransactional(name = "fsp-create-order",rollbackFor = Exception.class)
    public String saveMerchandiseOrder(MerchandiseOrder  merchandiseOrder,OrderVo orderVo) throws ExecutionException {
        //重新填入
        MerchandiseOrder merchandiseOrderAutowired = new MerchandiseOrder();
        merchandiseOrderAutowired.setAId(orderVo.getAId());
        merchandiseOrderAutowired.setDId("211"+UUIDGenerator.getUUID7());//生成8位+UUID封装
        merchandiseOrderAutowired.setDPiece(orderVo.getDPiece());
        merchandiseOrderAutowired.setPId(orderVo.getPid());
        merchandiseOrderAutowired.setDTotal(orderVo.getDTotal());
        //订单状态
        merchandiseOrderAutowired.setDStatus(ResultCodeEnum.PAY_TREAT.getMessage());
        //执行rabbitmq
        // 同步等待，可以设置为异步回调
        CorrelationData correlationData = new CorrelationData();
        rabbitTemplate.convertAndSend("x.order","k.order",merchandiseOrderAutowired,correlationData);
        //同步等待,可以设置异步回调
        CorrelationData.Confirm confirm = null;
        try {
            confirm = correlationData.getFuture().get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 判断发送的消息是否得到broker的确认
        boolean confirmAck = confirm.isAck();
        if(!confirmAck){
            throw  new BigException(ResultCodeEnum.CREATE_ORDER_FAIL);
        }

        // 发送延迟等待消息
        rabbitTemplate.convertAndSend("x.ttl","k.ttl" , merchandiseOrderAutowired.getDId());
        //写入数据库
        System.out.println("merchandiseOrderAutowired；\t"+merchandiseOrderAutowired);
        baseMapper.insert(merchandiseOrderAutowired);
        // 发送短信
        PatientInfo userById = patientFeignClient.findUserById(String.valueOf(orderVo.getPid()));
        PaySmsVo paySmsVo = new PaySmsVo();
        paySmsVo.setDid(merchandiseOrderAutowired.getDId());//订单流水号
        paySmsVo.setTotalMoney(merchandiseOrderAutowired.getDTotal());//金额
        paySmsVo.setWeb("idea");
        paySmsVo.setMobile(userById.getPhone());
        //发送短信消费队列
//      rabbitTemplate.convertAndSend(RabbitConfig.EXCHANGE_DIRECT_MSM,RabbitConfig.ROUTING_MSM_ITEM,paySmsVo);

        return merchandiseOrderAutowired.getDId();
    }

    /**
     * 修改订单状态
     * @param orderId
     */
    @Override
    public Integer upOrderStatus(String orderId,ResultCodeEnum resultCodeEnum) {
        UpdateWrapper<MerchandiseOrder> updateWrap=new UpdateWrapper<>();
        updateWrap.eq("d_id",orderId).set("d_status",resultCodeEnum.getMessage());
       return baseMapper.update(null, updateWrap);
    }


    /**
     * 查询订单
     * @param orderId
     * @return
     */
    @Override
    public MerchandiseOrder infoMerchandiseOrder(String orderId) {
        QueryWrapper<MerchandiseOrder> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(orderId)){
            wrapper.eq("d_id",orderId);
        }
        return  baseMapper.selectOne(wrapper);
    }


    /**
     * 订单列表
     * @param uid
     */
    @Override
    public List<MerchandiseOrder> infoMerchandiseOrders(String uid) {
        QueryWrapper<MerchandiseOrder>queryWrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(uid)){
         queryWrapper.eq("p_id",uid);
        }
        List<MerchandiseOrder> merchandiseOrders = baseMapper.selectList(queryWrapper);
        merchandiseOrders.forEach(item -> {
              this.infoMerchandiseOrdersOrderRecords(item);
        });
        return merchandiseOrders;
    }

    /**
     * 后台订单列表
     * @param pageParam
     * @param orderInfoQueryVo
     * @return
     */
    @Override
    public IPage<MerchandiseOrder> selectPage(Page<MerchandiseOrder> pageParam, OrderInfoQueryVo orderInfoQueryVo) {
        //orderInfoQueryVo获取条件值
        Long Id = orderInfoQueryVo.getId(); //订单编号
        Integer status = orderInfoQueryVo.getStatus();//订单状态
        Integer authStatus = orderInfoQueryVo.getAuthStatus(); //认证状态
        String createTimeBegin = orderInfoQueryVo.getCreateTimeBegin(); //开始时间
        String createTimeEnd = orderInfoQueryVo.getCreateTimeEnd(); //结束时间
        //对条件值进行非空判断
        QueryWrapper<MerchandiseOrder> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(Id)) {
            wrapper.like("d_id",Id);
        }
        if(!StringUtils.isEmpty(status)) {
            wrapper.eq("is_deleted",status);
        }
        if(!StringUtils.isEmpty(authStatus)) {
            wrapper.eq("d_status",authStatus);
        }
        if(!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.ge("create_time",createTimeBegin);
        }
        if(!StringUtils.isEmpty(createTimeEnd)) {
            wrapper.le("create_time",createTimeEnd);
        }
        //调用mapper的方法
        IPage<MerchandiseOrder> pages = baseMapper.selectPage(pageParam, wrapper);
        return pages;
    }


    /**
     * 订单商品记录列表
     */
    public MerchandiseOrder infoMerchandiseOrdersOrderRecords(MerchandiseOrder merchandiseOrder){
        List<MerchandiseOrderRecord> merchandiseOrderRecordList = merchandiseOrderRecordService.infoMerchandiseOrderRecords(merchandiseOrder.getDId());
        merchandiseOrder.getParam().put("merchandiseOrderRecords",merchandiseOrderRecordList);
     return  merchandiseOrder;
    }


    /**
     * 后台
     * 订单详情
       组装方法
     */
    @Override
    public   MerchandiseOrder adminOrderInfo(String orderId){
        MerchandiseOrder merchandiseOrder = this.infoMerchandiseOrder(orderId); //获取订单信息
        //获取用户信息
        PatientInfo patientInfo = patientFeignClient.findUserById(String.valueOf(merchandiseOrder.getPId()));
        //获取地址信息
        PatientAddress patientAddress = patientFeignClient.addressInfo(merchandiseOrder.getAId());
        //转换数据字典cod
        this.dicts(patientAddress);
        //获取商品列表
        List<MerchandiseOrderRecord> merchandiseOrderRecord = merchandiseOrderRecordService.infoMerchandiseOrderRecords(merchandiseOrder.getDId());
        merchandiseOrderRecord.forEach(item -> {
            MerchandiseDetail merchandiseDetail = merchandiseFeignClient.FindMerchanInfo(String.valueOf(item.getMId()));
           this.dises(merchandiseDetail,item);
        });
        merchandiseOrder.getParam().put("patient",patientInfo);
        merchandiseOrder.getParam().put("patientAddress",patientAddress);
        merchandiseOrder.getParam().put("merchandiseOrderRecord",merchandiseOrderRecord);

        //TODO 如果已经支付了,就获取交易记录信息
        if( merchandiseOrder.getDStatus().equals("待发货")||
            merchandiseOrder.getDStatus().equals("已发货")||
            merchandiseOrder.getDStatus().equals("已签收")||
            merchandiseOrder.getDStatus().equals("已退款")){
            //填入交易记录
            AlipayTradeQueryResponseVo alipayTradeQueryResponseVo = payFeignClient.payInfo(orderId);
            merchandiseOrder.getParam().put("alipayTrade",alipayTradeQueryResponseVo);
        }

        return merchandiseOrder;
    }

    @Override
    public boolean upShipments(String phone, String oId) {
        UpdateWrapper<MerchandiseOrder> updateWrapper=new UpdateWrapper<>();
        updateWrapper.eq("d_id",oId).set("d_status",ResultCodeEnum.PAY_RUIN.getMessage());
        int update = baseMapper.update(null, updateWrapper);
        if(update>0){
            Integer shipments = smsFeignClient.shipments(phone, oId);
            return  shipments==0 ?true:false;
        }
        return false;
    }


    //订单签收
    @Override
    public boolean signOrder(MerchanCommVo merchanCommVo) {

        //查询订单信息
        MerchandiseOrder merchandiseOrder = this.infoMerchandiseOrder(merchanCommVo.getOidVal());
        //查询商品组
        List<MerchandiseOrderRecord> merchandiseOrderRecordList = merchandiseOrderRecordService.infoMerchandiseOrderRecords(merchanCommVo.getOidVal());
        merchandiseOrderRecordList.forEach(item -> {
            MerchandiseComment merchandiserComment=new MerchandiseComment();
            merchandiserComment.setContent(merchanCommVo.getContentVal());
            merchandiserComment.setPId(merchandiseOrder.getPId());
            merchandiserComment.setMId(item.getMId());
            merchandiseFeignClient.saveComment(merchandiserComment);
        });
        UpdateWrapper<MerchandiseOrder> updateWrap=new UpdateWrapper<>();
        updateWrap.eq("d_id",merchandiseOrder.getDId()).set("d_status",ResultCodeEnum.PAY_RUN.getMessage());
        return baseMapper.update(null, updateWrap)>=1 ? true : false;
      }

    public  PatientAddress dicts(PatientAddress patientAddress){
        log.info("值{}",patientAddress);
        String province = dictFeignClient.getName(String.valueOf(patientAddress.getProvinceCode()));
        String city = dictFeignClient.getName(String.valueOf(patientAddress.getCityCode()));
        String district = dictFeignClient.getName(String.valueOf(patientAddress.getDistrictCode()));
        patientAddress.getParam().put("province",province);
        patientAddress.getParam().put("city",city);
        patientAddress.getParam().put("district",district);
        return patientAddress;
    }

    public  MerchandiseOrderRecord dises(MerchandiseDetail merchandiseDetail,MerchandiseOrderRecord merchandiseOrderRecord ){
        String cateName = dictFeignClient.getName(String.valueOf(merchandiseDetail.getCateId()));
        merchandiseOrderRecord.getParam().put("cateName",cateName);
        return merchandiseOrderRecord;
    }

}

